//
//  UserGiftView.swift
//  koolcar
//
//  Created by xiantian on 2023/11/1.
//

import UIKit
import MJRefresh
typealias ExchangePointBlock = ()->Void
class UserGiftView: UIView {
    var exchangePointSuccessBlock: ExchangePointBlock?
    var emptyView: LYEmptyView!
    var tableView: BaseTableView!
    var dataArray: [IntegralProductDataContentModel] = []
    override init(frame: CGRect) {
        super.init(frame: frame)
        tableView = BaseTableView.init(frame: CGRect.init(x: 0, y: 0, width: kScreenWidth, height: frame.size.height), style: .grouped)
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
        tableView.register(UserGiftCell.self, forCellReuseIdentifier: "UserGiftCell")
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = Theme.whiteColor
        tableView.separatorStyle = .none
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = 128
        self.addSubview(tableView)
        
        self.setUpNoData()
        self.addPullRefreash()
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        self.tableView.frame = self.bounds
    }
    
    ///MARK: - 下拉刷新
    func addPullRefreash()  {
        weak var weakself = self
        let headerR = MJRefreshNormalHeader.init(refreshingBlock: {
            weakself!.fetchGetGiftList()
        })
        headerR?.activityIndicatorViewStyle = .gray
        self.tableView.mj_header = headerR
    }
    
    ///空视图
    func setUpNoData() {
        self.emptyView = LYEmptyView.emptyActionView(withImageStr: "icon_empty", titleStr: MMLocalizedString("no_more_data", comment: "暂时没有数据"), detailStr: "", btnTitleStr: "") {
            
        }
        emptyView?.subViewMargin = 28;
        emptyView?.contentViewOffset = -100
        self.tableView.ly_emptyView = self.emptyView
    }
    
    ///空视图
    func willShowEmptyView() {
        if self.dataArray.count == 0 {
            self.tableView.mj_footer?.isHidden = true
            self.emptyView.isHidden = false
            self.emptyView?.titleStr = MMLocalizedString("no_data", comment: "暂无数据")
        }else{
            self.emptyView.isHidden = true
            self.emptyView?.titleStr = ""
        }
    }
    
    ///
    func changeGifItem(){
        if self.dataArray.count > 0 {
            return
        }
        self.fetchGetGiftList()
    }
    
    ///获取列表
    private func fetchGetGiftList(){
        var param = NSMutableDictionary() as! [String: String]
        param["pageSize"] = "9999"
        param["pageNumber"] = "1"
        param["orderType"] = ""
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.integralProductPage(param: param), objectType: IntegralProductResModel.self) { data in
            self.tableView.mj_header?.endRefreshing()
            let resultObj = data as! IntegralProductResModel
            if resultObj.code == "1" {
                self.dataArray = resultObj.data?.content ?? []
                self.dataArray.forEach { item in
                    item.exchangeNowBlock = { [weak self] in
                        self?.handleExchangeNow(item: item)
                    }
                }
                self.tableView.reloadData()
            }else{
                self.viewController().view?.makeToast(message: resultObj.msg ?? "")
            }
        } error: { err in
            self.tableView.mj_header?.endRefreshing()
            self.viewController().view?.makeToast(message: err?.domain ?? "")
        }
    }
    
    ///立即兑换
    func handleExchangeNow(item: IntegralProductDataContentModel){
        let tempMsg = String(format: MMLocalizedString("exchange_point_tip", comment: "确定使用%.0f积分兑换%@吗？"), item.integralValue ?? 0, item.integralName ?? "")
        
        
        CouponAlertView.showAlertView(title: MMLocalizedString("hint", comment: "提示"),
                                      message: tempMsg,
                                      cancelButtonTitle: MMLocalizedString("cancel", comment: "取消"),
                                      otherButtonTitlesArr: [MMLocalizedString("confirm", comment: "确定")]) { tag, _ in
            if tag == 1 {
                self.handleExchangeRequest(pId: item.id ?? 0)
            }
        }
        
    }
    
    private func handleExchangeRequest(pId: NSInteger){
        self.viewController().view?.showLoadingHUDText()
        let param:[String: String] = ["id": "\(pId)"]
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.createIntegralOrder(param: param), objectType: CommondResModel.self) { data in
            self.viewController().view?.handleLoading()
            let resultObj = data as! CommondResModel
            if resultObj.code == "1" {
                self.viewController().view.makeToast(message: MMLocalizedString("exchange_success", comment: "兑换成功"))
                self.exchangePointSuccessBlock?()
            }else{
                self.viewController().view?.makeToast(message: resultObj.msg ?? "")
            }
        } error: { err in
            self.viewController().view?.handleLoading()
            self.viewController().view?.makeToast(message: err?.domain ?? "")
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}


extension UserGiftView: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataArray.count
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return IphoneXMarginBottom + 34
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "UserGiftCell", for: indexPath) as! UserGiftCell
        if self.dataArray.count > indexPath.row {
            let model = self.dataArray[indexPath.row]
            cell.setUserGiftCell(data: model)
        }
        cell.updateConstraints()
        cell.selectionStyle = .none
        cell.clipsToBounds = true
        return cell
    }
}
